import cv2

# 打开默认摄像头
cap = cv2.VideoCapture(0)

if not cap.isOpened():
    print("无法打开摄像头")
    exit()

# 获取帧的宽度和高度
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

# 定义输出视频文件的参数
out = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), 30, (frame_width, frame_height))

while True:
    # 读取一帧
    ret, frame = cap.read()
    
    # 检查是否成功读取帧
    if not ret:
        print("无法获取帧")
        break
    
    # 写入帧到视频文件
    out.write(frame)
    
    # 显示帧
    cv2.imshow('Camera Feed', frame)
    
    # 按下 'q' 键退出循环
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放捕获对象和写入对象，并关闭所有窗口
cap.release()
out.release()
cv2.destroyAllWindows()